package com.pishou.shop;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pishou.URLConfig;
import com.pishou.code.bean.Cart;
import com.pishou.code.bean.Comment;
import com.pishou.code.util.HttpPostClient;
import com.pishou.player.ComentVideoActivity;
import com.pishou.player.R;
import com.pishou.code.bean.Product;
import com.pishou.Data;
import com.pishou.player.TextureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class DetailActivity extends Activity {

    public static Product product;
    private float mPosX;
    private float mCurrentPosX;
    private boolean left_move_action = false;

    private Timer timer;
    private TimerTask task;

    private ScrollView sv_cart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        // 设置回退Icon
        TextView tv_detail_back = (TextView)findViewById(R.id.tv_detail_back);
        tv_detail_back.setTypeface(font);
        // 设置评论Icon
        TextView tv_detail_comment = findViewById(R.id.tv_detail_comment);
        tv_detail_comment.setTypeface(font);
        // 设置详情Icon
        TextView tv_detail_image = findViewById(R.id.tv_detail_image);
        tv_detail_image.setTypeface(font);
        // 获取上一个页面传递的SKU
        Intent intent = getIntent();
        Long  sku = intent.getLongExtra("sku",0);
        // 根据SKU获取产品信息
        product = Data.getProduct(sku);
        // 将产品信息展示在页面上
        ImageView iv_detail_image = (ImageView) findViewById(R.id.iv_detail_image);
        setImage(iv_detail_image, URLConfig.oss_host+"image/"+product.getSku()+".jpg",true,500,500);
        TextView tv_detail_price = (TextView)findViewById(R.id.tv_detail_price);
        tv_detail_price.setText("¥ " + product.getPrice());
        TextView tv_detail_detail = (TextView)findViewById(R.id.tv_detail_detail);
        tv_detail_detail.setText(product.getName());

        // 展示评论
        ListView lv_detail_comment = findViewById(R.id.lv_detail_comment);
        lv_detail_comment.setAdapter(new MyCommentAdapt());
        setListViewHeightBasedOnChildren(lv_detail_comment);
        lv_detail_comment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (new Integer(1).equals(product.getComments().get(position).getVideo())){
                    Intent intent = new Intent(getApplicationContext(), ComentVideoActivity.class);
//                    Intent intent = new Intent(getApplicationContext(), CommentVideoSurfaceActivity.class);
                    intent.putExtra("current",product.getVideoPathCurrent(product.getComments().get(position).getId()));
                    intent.putExtra("videoPaths",product.getVideo_paths());
                    Data.current_product_comment_video = product.getVideo_comment();
                    startActivity(intent);
                }else{
                    return ;
                }
            }
        });
        // 展示详情
        if (product.getDetails()!=null && product.getDetails().size()>0){
            ListView lv_detail_image = (ListView) findViewById(R.id.lv_detail_image);
            lv_detail_image.setAdapter(new MyDetailImageAdapt());
            setListViewHeightBasedOnChildren(lv_detail_image);
        }

        // 构建底部图片
        ImageView bottomImage = (ImageView) findViewById(R.id.iv_bottomImage);
        setImage(bottomImage, URLConfig.oss_host + "eshop/slide-1.jpg",false,null,null);

        initCart();
        sv_cart = findViewById(R.id.sv_cart);
    }

    public void sendToSalesclerk(View v) {
        new Thread() {
            @Override
            public void run() {
                String param = "storeId=1&no=1&sku=" + product.getSku() + "&name=" + product.getName();
                String re = HttpPostClient.sendPost(URLConfig.url_details_send, param);
                final JSONObject result = JSON.parseObject(re);
                if (result.getInteger("success").equals(1)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"发送成功",Toast.LENGTH_SHORT).show();                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"发送失败："+result.getString("msg"),Toast.LENGTH_SHORT).show();                        }
                    });
                }
                super.run();
            }
        }.start();
    }

    @Override
    protected void onPause() {
        if (timer!=null){
            timer.cancel();
            timer = null;
        }
        if (task!=null){
            task.cancel();
            task = null;
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        timer = new Timer();
        task = new TimerTask(){
            @Override
            public void run() {
                //Toast.makeText(getApplicationContext(),"退回广告页面",Toast.LENGTH_SHORT).show();
                // 跳转到播放广告页面，设置该Activity为第一个页面，清空它上面的栈
                Intent intent= new Intent(getApplicationContext(), TextureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        };
        timer.schedule(task,15*1000l);
        super.onResume();
    }

    /**
     * 返回上一页
     * @param v
     */
    public void  back(View v){
        finish();
    }

    /**
     * 加入购物车
     * @param v
     */
    public void addToCart(View v){
        try{
            Data.addCart(product);
            initCart();
            Toast.makeText(this,"加入购物车成功",Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,"加入购物车失败",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 跳转到结算界面
     * @param v
     */
    public void pay(View v){
        Intent intent = new Intent(this,PayActivity.class);
        startActivity(intent);
    }

    /**
     * 触屏，重置返回到播放广告页面
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN){
            if (timer != null){
                timer.cancel();
                timer = null;
            }
            if (task != null){
                task.cancel();
                task = null;
            }
            timer = new Timer();
            task = new TimerTask(){
                @Override
                public void run() {
                    Intent intent= new Intent(getApplicationContext(), TextureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            };
            if (timer!=null && task!=null){
                timer.schedule(task,15*1000l);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 设置图片
     * @param iv
     * @param path
     */
    private synchronized void setImage(final ImageView iv,  final String path, final Boolean scal_flag, final Integer width, final Integer height) {
        new Thread(){
            @Override
            public void run() {
                File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(),Base64.DEFAULT));
                if (!file.exists()){
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        int code = conn.getResponseCode();
                        if (code == 200){
                            InputStream in = conn.getInputStream();
                            int len = -1;
                            byte[] buffer = new byte[1024];
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((len = in.read(buffer))!=-1) {
                                fos.write(buffer, 0, len);
                            }
                            fos.close();
                            in.close();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (iv!=null){
                    if (scal_flag){
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(file.getAbsolutePath(),options);
                        int w = options.outWidth;
                        int h = options.outHeight;
                        // 计算缩放比
                        int scalX = 0;
                        if (width != null && width != 0){
                            scalX = w/width;
                        }
                        int scalY = h/height;
                        int scal = 1;
                        // 计算宽和高的缩放比，选择缩放比较大的使用
                        if (scalX>scalY && scalX>scal) {
                            scal = scalX;
                        }
                        if (scalY > scalX && scalY > scal) {
                            scal = scalY;
                        }
                        options.inSampleSize = scal;
                        // 取消不读取图片的设置，并且携带缩放比读取图片
                        options.inJustDecodeBounds = false;
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }else{
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }
                }
                super.run();
            }
        }.start();
    }

    /**
     * 设置ScrollView中ListView的高度
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 实例化购物车
     */
    private void initCart(){
        LinearLayout ll_cart = (LinearLayout) findViewById(R.id.ll_cart);
        ll_cart.removeAllViews();
        for (Cart cart:Data.carts){
            View view = View.inflate(getApplicationContext(),R.layout.cart_item,null);
            ImageView image = (ImageView)view.findViewById(R.id.cart_image);
            setImage(image, URLConfig.oss_host + "image/" + cart.getProduct().getSku()+".jpg",true,0,150);
            image.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            mPosX = event.getX();
                            left_move_action = true;
                            break;
                        case MotionEvent.ACTION_MOVE:
                            mCurrentPosX = event.getX();
                            if (mPosX - mCurrentPosX  > 100 && left_move_action){
                                left_move_action = false;
                                // 购物车减1
                                int index = ((ViewGroup)view.getParent().getParent()).indexOfChild((View)view.getParent());
                                Data.reduceCart(index);
                                initCart();
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
            TextView quantity = (TextView) view.findViewById(R.id.cart_quantity);
            quantity.setText(cart.getQuantity().toString());
            ll_cart.addView(view);
        }
        TextView tv_cart_js = (TextView) findViewById(R.id.tv_cart_js);
        tv_cart_js.setText("¥ " + Data.cartTotal +"\n结算");
        if (Data.cartTotal>0){
            tv_cart_js.setClickable(true);
            tv_cart_js.setBackgroundColor(getResources().getColor(R.color.enable));
        }else{
            tv_cart_js.setClickable(false);
            tv_cart_js.setBackgroundColor(getResources().getColor(R.color.black_overlay));
        }
    }

    /**
     * 评论ListView的适配器
     */
    private class MyCommentAdapt extends BaseAdapter{
        @Override
        public int getCount() {
            return product.getComments().size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView==null){
                view = View.inflate(getApplicationContext(),R.layout.comment_item,null);
            }else{
                view = convertView;
            }
            Comment comment = product.getComments().get(position);
            ImageView iv_comment_head = (ImageView)view.findViewById(R.id.iv_comment_head);
            setImage(iv_comment_head,comment.getHead(),true,0,100);
            TextView tv_comment_name = (TextView)view.findViewById(R.id.tv_comment_name);
            tv_comment_name.setText(comment.getName());
            TextView tv_comment_content = (TextView)view.findViewById(R.id.tv_comment_content);
            tv_comment_content.setText(comment.getContent());
            LinearLayout ll = (LinearLayout)view.findViewById(R.id.ll_comment_imageGroup);
            for (int i=0;i<comment.getPicture();i++){
                ImageView image = (ImageView)ll.getChildAt(i);
                setImage(image, URLConfig.oss_host+"comment/"+(i+1)+"/"+comment.getId()+".jpg",true,0,300);
            }
            return view;
        }
    }

    private class MyDetailImageAdapt extends BaseAdapter{
        @Override
        public int getCount() {
            return product.getDetails().size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                view = View.inflate(getApplicationContext(), R.layout.image_item, null);
            } else {
                view = convertView;
            }
            ImageView iv_detailImage = (ImageView) view.findViewById(R.id.iv_detailImage);
            setImage(iv_detailImage,product.getDetails().get(position),false,null,null);
            return view;
        }
    }

}
